package com.penghk.earth.jsch;

import com.jcraft.jsch.*;

/**
 * 采用Java模拟shell操作
 */
public class Shell {

    private static final String USER="penghk";
    private static final String PASSWORD="123qwe";
    private static final String HOST="127.0.0.1";
    private static final int DEFAULT_SSH_PORT=22;

    public static void main(String[] args) throws JSchException {
        Shell shell = new Shell();
        shell.doShell();
    }
    public void doShell() throws JSchException {
        JSch jsch=new JSch();
        Session session = jsch.getSession(USER,HOST,DEFAULT_SSH_PORT);
        session.setPassword(PASSWORD);
        UserInfo userInfo = new LocalUserInfo();
        session.setUserInfo(userInfo);

        // It must not be recommended, but if you want to skip host-key check,
        // invoke following,
        // session.setConfig("StrictHostKeyChecking", "no");

        //session.connect();
        session.connect(30000);   // making a connection with timeout.

        Channel channel=session.openChannel("shell");

        // Enable agent-forwarding.
        //((ChannelShell)channel).setAgentForwarding(true);

        channel.setInputStream(System.in);
        channel.connect(3*1000);
    }

    class LocalUserInfo implements UserInfo {

        @Override
        public String getPassphrase() {
            System.out.println("getPassphrase");
            return null;
        }
        @Override
        public String getPassword() {
            System.out.println("getPassword");
            return null;
        }
        @Override
        public boolean promptPassword(String s) {
            System.out.println("promptPassword:"+s);
            return false;
        }
        @Override
        public boolean promptPassphrase(String s) {
            System.out.println("promptPassphrase:"+s);
            return false;
        }
        @Override
        public boolean promptYesNo(String s) {
            System.out.println("promptYesNo:"+s);
            return true;//notice here!
//            return false;//notice here!

        }
        @Override
        public void showMessage(String s) {
            System.out.println("showMessage:"+s);
        }
    }
}
